package com.gu.myviewmodel.ui.homepage.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import com.gu.myviewmodel.base.BaseFragment
import com.gu.myviewmodel.databinding.FragmentMainBinding
import com.gu.myviewmodel.services.Car
import com.gu.myviewmodel.ui.homepage.model.MainViewModel
import com.gu.myviewmodel.ui.homepage.model.MainViewModel.LoadType

import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MainFragment : BaseFragment() {
    private val viewModel: MainViewModel by viewModels()

    @Suppress("UNCHECKED_CAST")
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        super.onCreateView(inflater, container, savedInstanceState)
        val binding = FragmentMainBinding.inflate(inflater, container, false)
        log("viewModel=$viewModel")
        binding.refreshBtn.setOnClickListener {
            getAdapter(binding).also {
                it.clear()
                it.refresh()
            }
            viewModel.loadAction.value = LoadType.REFRESH
        }
        viewModel.loading.observe(viewLifecycleOwner) { isLoading ->
            binding.pb.visibility = if (isLoading) View.VISIBLE else View.GONE
        }
        binding.rv.adapter = CarAdapter()

        viewModel.data.observe(viewLifecycleOwner) { res ->
            if (res.isSuccess) {
                val list = res.getOrNull() as List<Car>
                list.forEach { log("$it") }
                with(getAdapter(binding)) {
                    bingData(list)
                    refresh()
                }
            } else {
                with(binding.errorTv) {
                    visibility = View.VISIBLE
                    text = res.exceptionOrNull()?.message
                }
            }
        }
        viewModel.loadAction.value = LoadType.INIT
        return binding.root
    }

    private fun getAdapter(binding: FragmentMainBinding): CarAdapter {
        return binding.rv.adapter as CarAdapter
    }

    override fun findTag() = TAG

    companion object {
        const val TAG = "MainFragment"
    }
}